package com.lkx.kafka.monitor.service;

import com.lkx.kafka.monitor.common.MemoryDataManager;
import com.lkx.kafka.monitor.dto.ThroughputMetrics;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class DataStorageService {
    @Autowired
    private MemoryDataManager memoryDataManager;

    @Autowired
    private FileStorageService fileStorageService;

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    @PostConstruct
    public void init() {
        // 启动时从文件加载数据
        loadDataFromFile();

        // 每30秒保存一次数据到文件
        scheduler.scheduleAtFixedRate(this::saveDataToFile, 30, 30, TimeUnit.SECONDS);
    }

    /**
     * 保存数据到内存
     */
    public void saveData(ThroughputMetrics metrics) {
        memoryDataManager.addData(metrics);
    }

    /**
     * 从内存获取数据
     */
    public List<ThroughputMetrics> getData(String topicName, Long startTime, Long endTime) {
        return memoryDataManager.getData(topicName, startTime, endTime);
    }

    /**
     * 保存数据到文件
     */
    private void saveDataToFile() {
        try {
            Map<String, List<ThroughputMetrics>> data = memoryDataManager.getAllData();
            fileStorageService.saveData(data);
        } catch (Exception e) {
            log.error("定时保存数据到文件失败", e);
        }
    }

    /**
     * 从文件加载数据
     */
    private void loadDataFromFile() {
        try {
            Map<String, List<ThroughputMetrics>> data = fileStorageService.loadData();
            memoryDataManager.setData(data);
        } catch (Exception e) {
            log.error("从文件加载数据失败", e);
        }
    }

    @PreDestroy
    public void destroy() {
        // 关闭前保存一次数据
        saveDataToFile();
        scheduler.shutdown();
    }
}
